package com.example.xinhuazidian.base

import com.example.xinhuazidian.bean.LatestBean
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers

/**
 * Description : BasePresenter
 */
open class BasePresenter<V : BaseView?>(baseView: V) {
    private var compositeDisposable: CompositeDisposable? = null

    /**
     * 返回 view
     */
    @JvmField
    var baseView: V?

    /**
     * 这个后面可以直接用   Example：apiServer.login(username, password)；
     */
    @JvmField
    protected var apiServer: API.Api = RetrofitService.instance!!.apiService

    /**
     * 解除绑定
     */
    fun detachView() {
        baseView = null
        removeDisposable()
    }

    fun addDisposable(observable: Observable<LatestBean?>?, observer: BaseObserver<LatestBean?>) {
        if (compositeDisposable == null) {
            compositeDisposable = CompositeDisposable()
        }
        if (observable != null) {
            compositeDisposable!!.add(
                observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(observer)
            )
        }
    }

    private fun removeDisposable() {
        if (compositeDisposable != null) {
            compositeDisposable!!.dispose()
        }
    }

    init {
        this.baseView = baseView
    }
}